package com.jxtti.interceptor;


import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jxtti.model.User;
import com.jxtti.utils.Constants;
import com.jxtti.utils.CookieUtil;


public class LoginInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private CookieUtil cookieUtil;

	/**
	 * 在DispatcherServlet完全处理完请求后被调用
	 */
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	/**
	 * 在业务处理器处理请求执行完成后,生成视图之前执行的动作
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
	}

	/**
	 * 在业务处理之前调用
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2) throws Exception {
		// 不过滤的uri,系统后期添加的不需过滤的action可在此列出
		String[] notInterceptor = new String[] {"/SiteIndex","/webcode", "/index", "/app/", "/login","/ueditor","/WebSubject","/WebIntranetPc" ,"/MicroSite"};
		// 请求的uri
		String uri = request.getRequestURI();

		// 是否过滤
		boolean doInterceptor = true;
		for (String s : notInterceptor) {
			if (uri.indexOf(s) != -1) {
				// 如果uri中包含不过滤的uri，则不进行过滤
				doInterceptor = false;
				break;
			}
		}

		if (doInterceptor) {
			// 从session获取用户信息
			HttpSession session = request.getSession();
			//Admin_User userInfo =(Admin_User)session.getAttribute("userInfo");	
			User userInfo=(User)session.getAttribute("userInfo");
			if (null == userInfo) {

				if (isAjax(request)) { // ajax
					PrintWriter printWriter = response.getWriter();
					printWriter.print("{sessionState:0}");
					printWriter.flush();
					printWriter.close();
					return false;
				} else {
					/*
					 * 自动登入 user为空，说明用户还没有登陆,就尝试得到浏览器传送过来的Cookie
					 * 不为空执行下面的方法,调用CookieUtil.java中的readCookieAndLogon方法
					 */
					try {
						long flag = cookieUtil.readCookieAndLogon(request,response);// 返回用户id：成功
						if (1 <= flag) {
							response.sendRedirect(Constants.SYSTEM_PATH	+ "AdminUser/mainInterface.htm");
							return false;
						} else {
							if (uri.equals(Constants.SYSTEM_PATH + "/")|| uri.equals(Constants.SYSTEM_PATH)) {
								if (cookieUtil.readCookieFlag(request,response, "reset") != 1) {// 是否是第一次跳转
									cookieUtil.saveCookieFlag("reset", response);
									response.sendRedirect(Constants.SYSTEM_PATH);
									return false;
								}
							} else {
								//response.sendRedirect(Constants.SYSTEM_PATH + "/login.jsp");
								response.sendRedirect(Constants.SYSTEM_PATH);
								return false;
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		return true;
	}

	private static boolean isAjax(HttpServletRequest request) {
		return request.getHeader("x-requested-with") != null
				&& request.getHeader("x-requested-with").equalsIgnoreCase(
						"XMLHttpRequest");
	}
}
